package com.example.mqtt_client.util;

import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

public abstract class DynamicScheduleTask implements SchedulingConfigurer {
    public abstract void scheduleWork();
    public abstract String getCron();

    /**
     * 执行定时任务
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> scheduleWork(),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 获取执行周期
                    String cron = getCron();
                    System.out.println("执行时间："+cron);
                    //2.2 合法性校验.
                    if (!StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}